package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.UnresolvedPermission;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-04-27
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    private MinioService minioService;

    @Override
    public String uploadPic(MultipartFile multipartFile) {

//        获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null || userId==0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
//        获取源文件名字
        String originalFilename = multipartFile.getOriginalFilename();
//        获取后缀
        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
        log.info("suffix=={}",suffix);
        String newFileName = UUID.randomUUID().toString()+"."+suffix;
//       上传，获取路径
        try {
            String url = minioService.uploadImgFile(null, newFileName, multipartFile.getInputStream());
//        保存数据
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(userId);
            wmMaterial.setUrl(url);
            wmMaterial.setType(0);
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setIsCollection(false);
            boolean b = save(wmMaterial);
            if(!b){
                log.error("保存失败");
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
            }
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("上传失败");
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }

    }

    /**
     * 分页查询--素材管理
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<WmMaterial> findByPage(WmMaterialDto dto) {
//        获取用户id,判断用户是否登录
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null || userId==0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 分页条件
        IPage<WmMaterial> iPage = new Page<>(dto.getPage(),dto.getSize());
        // 设置查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmMaterial::getUserId,userId);
        if(dto.getIsCollection() != null && dto.getIsCollection() != 0 ){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        // 查询素材表 得到对象
        IPage<WmMaterial> materialIPage = page(iPage, queryWrapper);
        if(materialIPage == null || CollectionUtils.isEmpty(materialIPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 返回结果
        return new PageResult<>(dto.getPage(),dto.getSize(),materialIPage.getTotal(),materialIPage.getRecords());



    }

    /**
     * 取消收藏-收藏
     * @param id
     */
    public  void updateCollect(Integer id, int isCollection) {
        // 获取用户id,判断是否登录
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null || userId==0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }

        // update wm_material set is_collection=? where id=? and user_id=?
        LambdaUpdateWrapper<WmMaterial> updateWrapper = new LambdaUpdateWrapper<>();
        // 比较完条件在修改状态
        updateWrapper
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,userId)
                .set(WmMaterial::getIsCollection,isCollection==1);
        boolean b = update(updateWrapper);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteWmMaterial(Integer id) {
        //        获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null || userId==0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        // 比较后修改状态
        queryWrapper
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,userId);
//        先查询素材
        WmMaterial wmMaterial = getOne(queryWrapper);
        if(wmMaterial == null){
            return ;
        }
        boolean b = remove(queryWrapper);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        删除minio的数据
        minioService.delete(wmMaterial.getUrl());
    }
}
